#! /usr/bin/env python
#
"""Poor man's substitute for "pickle", supporting Cython classes.
"""
__docformat__ = 'reStructuredText'


import os
from zlib import adler32


cdef list load(filename):
    cdef long checksum
    cdef list result
    cdef object checkpoint_file
    cdef object checksum_file
    cdef object error

    
    try:
        result = list()
        checksum = 0
        checkpoint_file = open(filename, 'r')
        for line in checkpoint_file:
            result.append(eval(line))
            checksum = adler32(line, checksum)

        checksum_file = open(filename+".sum", 'r')
        if checksum != int(checksum_file.read(), 16):
            return None

        # checksum ok, return to caller
        return result
    except IOError, error:
        if error.errno == 2: # No such file or directory
            return None
        else:
            raise error
    finally:
        try:
            checkpoint_file.close()
            checksum_file.close()
        except:
            pass
        

cdef void save(list items, filename):
    cdef long checksum
    cdef object checkpoint_file
    cdef object checksum_file
    cdef object line

    checksum = 0
    try:
        checkpoint_file = open(filename, 'w')
        for item in items:
            line = "%s\n" % repr(item)
            checksum = adler32(line, checksum)
            checkpoint_file.write(line)
        checkpoint_file.close()
        checksum_file = open(filename+".sum", 'w')
        checksum_file.write("0x%x\n" % checksum)
        checksum_file.close()
    except Exception, error:
        # remove file to avoid corrupted restart
        try:
            os.remove(filename)
            os.remove(filename+".sum")
        except:
            pass
        raise error



## main: run tests

if "__main__" == __name__:
    import doctest
    doctest.testmod(name="loadsave",
                    optionflags=doctest.NORMALIZE_WHITESPACE)
